<template>
  <div class="batch-task-dialog">
    <el-dialog :visible.sync="dialogFormVisible"
               :append-to-body="true"
               :close-on-click-modal="false"
               class="custom-dialog"
               @close="close"
               @open="open">
      <div slot="title">
        <div style="color:#fff">{{title}}</div>
      </div>
      <div>
        <el-card>
          <div style="display:flex;align-items:center">
            <div style="width:150px">
              <el-tooltip class="item" effect="dark" :content="totalAreaLabels.toString()" placement="right">
                <el-tag size="medium">处理地块</el-tag>
              </el-tooltip>
            </div>
            <div style="flex:1;text-align: right;font-size:24px;font-weight: bolder">
              {{totalArea}}亩/{{totalAreaCount}}块
            </div>
          </div>
        </el-card>
        <div style="height:20px"></div>
        <el-card>
          <div style="display: flex;width: 100%">
            <div style="display: flex;flex: 1">
              <el-button type="primary" icon="el-icon-download" plain @click="handleClickDown" style="margin-right: 10px">下载导入模板</el-button>
              <el-upload
                ref="exportUpload"
                action="exportExcel"
                :multiple="false"
                :limit="1"
                :show-file-list="false"
                :http-request="uploadSectionFile">
                <el-button type="primary" icon="el-icon-upload" plain>导入农事任务</el-button>
              </el-upload>
            </div>
            <div style="display: flex;flex: 1;justify-content: flex-end">
              <el-button type="primary" icon="el-icon-plus" plain @click="handleClickAddNewTask">添加新的农事任务</el-button>
            </div>
          </div>
          <div>
            <div
              v-for="item in taskItemList" :key="item.key"
              style="border:1px solid #5daf34;border-radius: 8px;margin-top: 20px;padding: 10px;display:flex;width:100%">
              <div style="flex:4;">
                <div style="display:flex;align-items:center;">
                  <div style="width: 100px">
                    <el-tag>{{item.farmName}}</el-tag>
                  </div>
                  <div>需要处理时间:&nbsp;<span>{{item.startTime}}——{{item.endTime}}</span></div>
                </div>
                <div style="margin-top: 20px;margin-bottom:10px;display:flex;align-items:center">
                  <div style="width:70px;">操作建议:&nbsp;</div>
                  <el-tooltip class="item" effect="dark" :content="item.proposal" placement="top">
                    <span
                      style="display:inline-block;width:580px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;height:20px;line-height:20px">
                      {{item.proposal}}
                    </span>
                  </el-tooltip>
                </div>
              </div>
              <div style="display:flex;align-items:center;flex:1;justify-content: flex-end">

                <el-button type="primary" plain style="margin-right:10px" @click="handleClickEditTask(item)">编&nbsp;辑</el-button>
                <el-popconfirm
                  title="确定要删除选中任务吗？"
                  @confirm="handleClickRemoveTask(item.key)"
                >
                  <el-button type="danger" plain slot="reference">删&nbsp;除</el-button>
                </el-popconfirm>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div slot="footer" style="margin-top:-20px">
        <el-button type="primary" @click="handleClickSubmit" :loading="addStatus">完&nbsp;&nbsp;成
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
    import {
        batchSaveTasks,
        downTaskTemplate,
        exportTaskTemplate
    } from '@/api/affairs'
    import PubSub from 'pubsub-js'
    import {
        FARM_TASK_OPEN_DIALOG,
        FARM_TASK_ADD_INFO
    } from '@/utils/publishId'
    import {getUUID} from "../../../../utils";

    export default {
        data() {
            return {
                addPublish: null,
                title: "批量下发任务",
                addStatus: false,
                dialogFormVisible: false,
                landList: [],
                totalAreaLabels: [],
                taskItemList: [],
                totalArea: 0,
                totalAreaCount: 0,
                totalAreaIds:[],
                taskTypeList:[],
            }
        },
        created(){
            this.addPublish = PubSub.subscribe(FARM_TASK_ADD_INFO, (msg, data) => {
                const {handleStartTime, type, handleEndTime, remarks, key} = data.info
                const farmItem = this.taskTypeList.find(i=>i.formCode== type)
                if(data.type=='add'){
                    const obj = {
                        key: getUUID(),
                        farmType: type,
                        farmName: farmItem.formName,
                        startTime: handleStartTime,
                        endTime: handleEndTime,
                        proposal: remarks
                    }
                    this.taskItemList.push(obj)
                }else{
                    let index = this.taskItemList.findIndex(item=>item.key==key)
                    this.taskItemList[index]['farmType'] = type
                    this.taskItemList[index]['farmName'] = farmItem.formName
                    this.taskItemList[index]['startTime'] = handleStartTime
                    this.taskItemList[index]['endTime'] = handleEndTime
                    this.taskItemList[index]['proposal'] = remarks
                    this.taskItemList[index]['key'] = getUUID()
                }
            })
        },
        beforeDestroy(){
            PubSub.unsubscribe(this.addPublish)
        },
        methods: {
            show(status, taskTypeList, obj) {
                this.landList = this.$cloneDeep(obj)
                this.taskTypeList = JSON.parse(JSON.stringify(taskTypeList))
                this.totalAreaLabels = []
                this.totalAreaIds = []
                this.totalArea = 0
                this.totalAreaCount = 0
                this.landList.forEach(item => {
                    this.totalArea += (item.area ? item.area*1 : 0)
                    this.totalAreaCount += 1
                    this.totalAreaLabels.push(item.label)
                    this.totalAreaIds.push(item.id)
                })

                this.dialogFormVisible = status
            },
            handleClickAddNewTask() {
                PubSub.publish(FARM_TASK_OPEN_DIALOG, {show: true, type: "add", item: this.taskTypeList})
            },
            handleClickEditTask(item){
                PubSub.publish(FARM_TASK_OPEN_DIALOG, {show: true, type: "edit", item: {taskList:this.taskTypeList, taskItem: JSON.parse(JSON.stringify(item))}})
            },
            handleClickSubmit() {
                if(this.taskItemList.length==0){
                    this.$message({type:"warn", message:"至少添加一项任务"})
                    return
                }
                this.addStatus = true

                const params = this.taskItemList.map(item=>{
                    const obj = {
                        farmType:item.farmType,
                        startTime:item.startTime,
                        endTime:item.endTime,
                        proposal:item.proposal
                    }
                    return obj
                })
                batchSaveTasks({
                    tasks: params,
                    ids:this.totalAreaIds
                }).then(res=>{
                    if(res.data.code && res.data.code==200){
                        this.$message({type:"success", message:res.data.msg})
                    }else{
                        this.$message({type:"error", message:res.data.msg})
                    }
                    this.addStatus = false
                    this.dialogFormVisible = false
                }).catch(err=>{
                    this.addStatus = false
                    this.dialogFormVisible = false
                    this.$message({type:"error", message:"批量添加报错："+err})
                })
            },
            handleClickDown() {
                window.open(downTaskTemplate())
            },
            handleClickRemoveTask(key){
                this.taskItemList.splice(this.taskItemList.findIndex(item=>item.key==key),1)
            },
            uploadSectionFile({file, onError, onSuccess}) {
                const fileName = file.name,
                    isXlsx = fileName.indexOf("xlsx") != -1
                // // 这里常规检验，看项目需求而定
                if (!isXlsx) {
                    this.$message.error("只能上传文档格式xlsx!");
                    return;
                }
                const formData = new FormData();
                formData.append("file", file)
                const loading = this.$load(this)
                exportTaskTemplate(formData).then(res => {
                    if (res.data.code == 200) {
                        if(res.data.data.length>0){
                            res.data.data.forEach(item=>{
                                // 农事类型  1-整地；2-施肥；3-播种；4-除草；5-病虫防止；6-水肥一体化；7-浇水；8-叶面肥；9-其它
                                // console.log("obj===>",this.taskTypeList.find(i=>i.formCode==item.farmType), item.farmType)
                                const obj = {
                                    key: getUUID(),
                                    farmType: item.farmTypeId,
                                    farmName: item.farmType,
                                    startTime: item.startTime,
                                    endTime: item.endTime,
                                    proposal: item.proposal
                                }
                                this.taskItemList.push(obj)
                            })
                        }
                    }
                    this.$refs.exportUpload.clearFiles()
                    loading.close()
                }).catch(err => {
                    console.log(err)
                    loading.close()
                    this.$message({type: 'error', message: "上传异常:" + err})
                })
            },
            open() {

            },
            close() {
                try{
                    this.$refs.exportUpload.clearFiles()
                }catch (e) {}
                this.addStatus = false
                this.dialogFormVisible = false
                this.landList = []
                this.totalAreaLabels = []
                this.taskItemList = []
                this.totalArea = 0
                this.totalAreaCount = 0
                this.taskTypeList = []
                this.taskItemList = []
            }

        }
    }
</script>

<style scoped>
  .custom-dialog >>> .el-dialog {
    width: 900px !important;
    position: relative;
  }

  .custom-dialog >>> .el-dialog__header {
    background: #009865;
    padding: 10px 10px 10px;
  }

  .custom-dialog >>> .el-dialog__headerbtn {
    top: 9px !important;
    right: 10px !important;
  }

  .custom-dialog >>> .el-dialog__body {
    line-height: 0px !important;
  }

  .custom-dialog >>> .el-input.is-disabled .el-input__inner {
    background-color: #fff;
    color: #606266;
  }

  .custom-dialog >>> .el-textarea.is-disabled .el-textarea__inner {
    background-color: #fff;
    color: #606266;
  }
</style>
